import json

import jwt
from django.http import HttpResponse
from jwt import PyJWTError

from .models import Project,StarsPro


def StarProject(request,id):
    body = json.loads(request.body)
    token = body["token"]
    try:
        user = jwt.decode(token, '79846517984651ryvgubhnj', algorithms=['HS256'])
    except PyJWTError:
        return HttpResponse("请重新登录", status=201)
    project = Project.objects.filter(id=id)
    if len(project) == 0:
        return HttpResponse("项目不存在", status=202)
    project = project[0]
    stars = StarsPro.objects.filter(project=project, user_id=user["id"])
    if request.method == 'POST':
        if len(stars) == 0:
            star = StarsPro(project=project,user_id=user["id"])
            star.save()
            project.stars += 1
            project.save()
            return HttpResponse("OK")
        return HttpResponse("已收藏过",status=201)
    if request.method == 'DELETE':
        if len(stars) != 0:
            star = stars[0]
            star.delete()
            project.stars -= 1
            project.save()
            return HttpResponse("OK")
        return HttpResponse("未收藏",status=201)

